package com.xaptul.filter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.ShallowEtagHeaderFilter;

/**
 * @author sugar_xj 这个类的作用就是给请求增加缓存
 */
public class XaptulEtagHeaderFilter extends ShallowEtagHeaderFilter {

	private Set<String> staticFiles = new HashSet<String>();

	private static String USER_AGENT = "user-agent";

	private static final String HEADER_EXPIRES = "Expires";

	private static final String HEADER_CACHE_CONTROL = "Cache-Control";

	/**
	 * 秒
	 */
	private int seconds = 0;

	/**
	 * 天
	 */
	private int staticFilesCache = 0;

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if (!"GET".equalsIgnoreCase(request.getMethod())) {
			filterChain.doFilter(request, response);// 非get请求没有必要生成 Etag
		} else {
			String browser = request.getHeader(USER_AGENT);
			if (browser != null && (browser.contains("MSIE 6.0")
					|| browser.contains("MSIE 7.0"))) {
				if (request.getProtocol().equals("HTTP/1.1")) {
					// HTTP 1.1 header 防止IE 不发请求 (对非静态文件)
					String headerValue = "max-age=" + seconds;
					response.setHeader(HEADER_CACHE_CONTROL, headerValue);
				}
			}
			String url = request.getRequestURI();
			for (String sfLocations : staticFiles) {
				if (url.startsWith(sfLocations)) {
					// HTTP 1.1 header 86400 秒= 1天 ,这里不需要考虑毫秒
					String headerValue = "max-age=" + staticFilesCache * 86400;
					response.setHeader(HEADER_CACHE_CONTROL, headerValue);
					break;
				}
			}
			super.doFilterInternal(request, response, filterChain);
		}
	}

	@Override
	protected void initFilterBean() throws ServletException {
		FilterConfig config = getFilterConfig();
		String cp = config.getServletContext().getContextPath();
		String cacheSeconds = config.getInitParameter("seconds");
		if (cacheSeconds != null) {
			seconds = Integer.parseInt(cacheSeconds);
			if (logger.isDebugEnabled()) {
				logger.debug(" setting cache seconds for " + seconds);
			}
		}
		String cacheDays = config.getInitParameter("staticFilesCache");
		if (cacheDays != null) {
			staticFilesCache = Integer.parseInt(cacheDays);
			if (logger.isDebugEnabled()) {
				logger.debug(" setting staticFilesCache days for "
						+ staticFilesCache);
			}
		}
		String staticFilesLocation = config
				.getInitParameter("staticFilesLocation");
		if (staticFilesLocation != null) {
			if (staticFilesLocation.contains(",")) {
				String[] locations = staticFilesLocation.split(",");
				for (String location : locations) {
					staticFiles.add(cp + location);
					if (logger.isDebugEnabled()) {
						logger.debug(" adding staticFilesLocation " + cp
								+ location);
					}
				}
			} else {
				if (!"".equals(staticFilesLocation)) {
					staticFiles.add(cp + staticFilesLocation);
					if (logger.isDebugEnabled()) {
						logger.debug(" adding staticFilesLocation " + cp
								+ staticFilesLocation);
					}
				}
			}
		}
		super.initFilterBean();
	}
}